package main

import (
    "net"
    "fmt"
    "time"
    "os"
)



func doTask(conn net.Conn) {
	buf := make([]byte, 1460)	//会自动释放，还不确认
	sendch := make(chan []byte)
    defer close(sendch)
    go doSend(sendch, conn)
    sendch <- str_test[0:]
    for {
	    n, err := conn.Read(buf[0:])
	    if err != nil {
	    	fmt.Println("rec goroutine close")
	 		//closeSocketCh(ch)
			return
	    }
	    fmt.Println("Reply form server", string(buf[0:n]))
	    sendch <- buf[0:n]
    }
}




func doSend(ch <-chan []byte, conn net.Conn) {
	
	tcnt2 := time.Tick(3000 * time.Millisecond)
	var sendStr string = "heart tick!"
	sendAr := []byte(sendStr) 
    for {
        select {
        case x, ok := <-ch:
            if !ok {
            	fmt.Println("send goroutine close")
                return
            }else {
				 //fmt.Println("send ", x)
        		conn.Write(x)
            }
        case <-tcnt2: 
        	fmt.Println(sendStr)
        	conn.Write(sendAr)
        }
    }
}





var str_test = []byte{0x02, 0x00, 0x0e, 0x51, 0x01 ,0x08, 0x01, 0x01, 0x02, 0x15, 0x08, 0x05, 0x50, 0x10, 0x01, 0x1a, 0x23}
    
func main() {
	service := "192.168.251.170:50002"
	addr, err := net.ResolveTCPAddr("tcp4", service)
    //hostInfo := "192.168.251.170.:50002"
	if err != nil {
        fmt.Fprintf(os.Stderr, "Fatal2 error: %s", err.Error())
        os.Exit(1)
    }

    for {
        conn,err := net.DialTCP("tcp", nil, addr)
        fmt.Print("connect (",service)
        if err != nil {
            fmt.Println(") fail")
        }else{
            fmt.Println(") ok")
            defer conn.Close()
            doTask(conn)
        }
        time.Sleep(2 * time.Second)
    }
}




